package com.health.mapp.impl;


import com.health.commons.PropertiesService;
import com.health.db.dto.DoctorListDto;
import com.health.db.dto.StuffDetailDto;
import com.health.db.model.UserLIST;
import com.health.db.model.UserLISTTemp;
import com.health.db.service.sm.IRongService;
import com.health.db.service.sm.IWXService;
import com.health.db.service.user.IStuffListService;
import com.health.db.service.user.IUserLISTService;
import com.health.mapp.bean.DocWeChatLoginReq;
import com.health.mapp.bean.DocWeChatLoginResp;
import com.health.mapp.bean.Header;
import com.health.mapp.bean.WXTokenModel;
import com.health.mapp.utils.Response;
import com.health.mapp.utils.ResultCode;
import io.rong.models.TokenReslut;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.util.TextUtils;

import java.util.List;

/**
 * Created by YYY on 2017/5/31.
 */
public class DocWeChatLoginImpl implements ActionInterface {

    private IWXService wxService;
    private IUserLISTService userLISTService;
    private IStuffListService stuffListService;
    private IRongService rongService;

    @Override
    public Response execute(Header header, Object reqBean) throws Exception {

        DocWeChatLoginReq req = (DocWeChatLoginReq) reqBean;
        DocWeChatLoginResp _resp = new DocWeChatLoginResp();

        WXTokenModel tokenModel = null;
        if (!TextUtils.isEmpty(req.getCode())) {
            tokenModel = wxService.getDocAccessToken(req
                    .getCode());
        } else if (TextUtils.isEmpty(req.getRefreshToken())) {
            //微信自动登录
            tokenModel = wxService.refreshDocToken(req.getRefreshToken());
        }

        if (null != tokenModel
                && !TextUtils.isEmpty(tokenModel.getAccess_token())
                && !TextUtils.isEmpty(tokenModel.getOpenid())) {
            UserLIST user = null;
            List<UserLIST> userLISTS = userLISTService.selectByWXOpenid(tokenModel
                    .getOpenid());
            if (null != userLISTS && userLISTS.size() > 0) {

                user = userLISTS.get(0);
            }

            if (user == null) {
                // 没有通过openid查询到相关用户 通知客户端绑定手机号
                _resp.setRefreshToken(tokenModel.getRefresh_token());
                _resp.setWxToken(tokenModel.getAccess_token());
                _resp.setErrorCode(-100);
                _resp.setErrorMsg("没有关联到相关账号信息 请绑定手机号");
                return _resp;
            } else {
                StuffDetailDto stuffDetail = stuffListService.selectByStuffId(user.getUserid());
                //登录信息
                UserLIST userLISTForUpdate = new UserLIST();
                DoctorListDto doctorListDto = packageDoctorListDto(stuffDetail);
                UserLISTTemp userLISTTemp = packageUserListDto(stuffDetail);


                if (StringUtils.isBlank(stuffDetail.getAppToken())) {
                    String iconUrl = stuffDetail.getIconUrl();

                    if (StringUtils.isBlank(iconUrl)) {
                        iconUrl = PropertiesService.getString("iconUrl.docDefaultUrl").trim();
                    }

                    /**
                     * token为空的话重新从融云获取Token
                     * */
                    TokenReslut tokenReslut = rongService.getUserToken(String.valueOf(stuffDetail.getStuffid()), stuffDetail.getStuffName(), iconUrl);
                    if (null != tokenReslut && tokenReslut.getCode().intValue() == 200) {

                        userLISTForUpdate.setApptoken(tokenReslut.getToken());
                        _resp.setErrorCode(ResultCode.OPERATION_SUCCESS);
                        _resp.setErrorMsg(ResultCode.OPERATION_SUCCESS_NOTE);
                        _resp.setUserId(String.valueOf(stuffDetail.getStuffid()));
                        _resp.setToken(tokenReslut.getToken());
                        _resp.setDoctor(doctorListDto);
                        _resp.setUser(userLISTTemp);
                        _resp.setWxToken(tokenModel.getAccess_token());
                        _resp.setRefreshToken(tokenModel.getRefresh_token());
                        return _resp;
                    } else {
                        _resp.setErrorCode(-1);
                        _resp.setErrorMsg("获取Token失败");
                        return _resp;
                    }
                } else {
                    _resp.setErrorCode(ResultCode.OPERATION_SUCCESS);
                    _resp.setErrorMsg(ResultCode.OPERATION_SUCCESS_NOTE);
                    _resp.setUserId(String.valueOf(stuffDetail.getStuffid()));
                    _resp.setToken(stuffDetail.getAppToken());
                    _resp.setDoctor(doctorListDto);
                    _resp.setUser(userLISTTemp);
                    _resp.setWxToken(tokenModel.getAccess_token());
                    _resp.setRefreshToken(tokenModel.getRefresh_token());
                    return _resp;
                }

            }


        } else {
            _resp.setErrorCode(-1);
            _resp.setErrorMsg("微信登录失败");
            return _resp;
        }
    }


    /**
     * javabean转换
     *
     * @param stuffDetail
     * @return
     */
    private DoctorListDto packageDoctorListDto(StuffDetailDto stuffDetail) {
        DoctorListDto doctorListDto = new DoctorListDto();

        doctorListDto.setDocId(String.valueOf(stuffDetail.getStuffid()));

        doctorListDto.setDocName(stuffDetail.getStuffName() == null ? "" : stuffDetail.getStuffName());
        doctorListDto.setDocTitle(stuffDetail.getStuffTitle() == null ? "" : stuffDetail.getStuffTitle());
        doctorListDto.setDocLabel(stuffDetail.getStuffLabel() == null ? "" : stuffDetail.getStuffLabel());
        doctorListDto.setDocImageUrl(stuffDetail.getIconUrl() == null ? "" : stuffDetail.getIconUrl());
        doctorListDto.setHospitalId(stuffDetail.getEntityid() == null ? 0 : stuffDetail.getEntityid());
        doctorListDto.setHospitalName(stuffDetail.getHospitalName() == null ? "" : stuffDetail.getHospitalName());
        doctorListDto.setDepartmentId(stuffDetail.getDepartmentid() == null ? 0 : stuffDetail.getDepartmentid());
        doctorListDto.setDepartmentName(stuffDetail.getDepartmentName() == null ? "" : stuffDetail.getDepartmentName());
        doctorListDto.setConsultScope(stuffDetail.getConsultRecommend() == null ? "" : stuffDetail.getConsultRecommend());

        return doctorListDto;
    }

    private UserLISTTemp packageUserListDto(StuffDetailDto stuffDetail) {

        UserLISTTemp user = new UserLISTTemp();
        user.setUserId(String.valueOf(stuffDetail.getStuffid()));
        user.setUserName(stuffDetail.getStuffName());
        user.setUserPhone(stuffDetail.getStuffNo());
        user.setRegTime(stuffDetail.getCreateDate());
        user.setIcon(stuffDetail.getIconUrl());

        return user;
    }

    public IWXService getWxService() {
        return wxService;
    }

    public void setWxService(IWXService wxService) {
        this.wxService = wxService;
    }

    public IUserLISTService getUserLISTService() {
        return userLISTService;
    }

    public void setUserLISTService(IUserLISTService userLISTService) {
        this.userLISTService = userLISTService;
    }

    public IStuffListService getStuffListService() {
        return stuffListService;
    }

    public void setStuffListService(IStuffListService stuffListService) {
        this.stuffListService = stuffListService;
    }

    public IRongService getRongService() {
        return rongService;
    }

    public void setRongService(IRongService rongService) {
        this.rongService = rongService;
    }
}
